<template>
  <div class="publish-container">
    <el-card>
      <!-- 头部 -->
  <template #header>
   <el-breadcrumb separator-class="el-icon-arrow-right">
     <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item>发布文章</el-breadcrumb-item>
   </el-breadcrumb>
  </template>
  <!-- 表单 -->
  <!-- 2.el-form标签上 ref="变量名" 绑定:rules="rules" -->
<el-form ref="publishFormRef" :model="publishForm" :rules="rules" label-width="3.333rem">
  <!-- 3.校验标题:el-form-item标题标签上 绑定prop="title" -->
  <el-form-item label="标题" prop="title">
    <el-input v-model="publishForm.title" placeholder="请输入标题"></el-input>
  </el-form-item>
  <!-- 5.选择频道校验:el-form-item标题标签上 绑定prop="channel_id" -->
  <el-form-item label="频道" prop="channel_id">
    <el-select clearable v-model="publishForm.channel_id" placeholder="请选择频道">
      <el-option v-for="obj in allChannelList" :key="obj.id" :label="obj.name" :value="obj.id"></el-option>
    </el-select>
  </el-form-item>
<!-- 6.选择封面校验:el-form-item标题标签上 绑定prop="cover.type" -->
  <el-form-item label="封面" prop="cover.type">
    <el-radio-group v-model="publishForm.cover.type" @change="onCoverTypeChangeFn">
      <el-radio v-for="obj in coverList" :key="obj.id" :label="obj.id">{{obj.name}}</el-radio>
    </el-radio-group>
    <div class="upload-container" v-if="publishForm.cover.type>=1">
      <el-upload
      :action="VUE_APP_UPLOAD_URL"
      list-type="picture-card"
      name="image"
      :before-upload="onBeforeUploadFn"
      :file-list="showFileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="onUploadRemoveFn"
      :on-success="onUploadSuccessFn"
      :limit="publishForm.cover.type"
      :on-exceed="onUploadExceedFn"
      >
     <i class="el-icon-plus"></i>
    </el-upload>
    </div>
  </el-form-item>
    <!-- 4.校验内容:富文本编辑器不属于el家,不能直接校验
    查文档Form Methods ->validateField 对部分表单字段进行校验的方法
    在标签中已写的change监听事件中加入校验内容 -->
  <el-form-item label="内容" prop="content">
    <quill-editor :value="publishForm.content" @change="onEditorChangeFn($event)">
    </quill-editor>
  </el-form-item>
  <el-form-item>
    <!-- 1.发布和修改用两个盒子分开写 -->
    <!-- 发布 -->
    <div class="publish-btn" v-if="!$route.query.targetId">
      <el-button type="primary" @click="publishArticleFn">发布文章</el-button>
      <el-button @click="publishArticleFn(true)">存入草稿</el-button>
    </div>
    <!-- 修改 -->
    <div class="update-btn" v-else>
      <el-button type="primary" @click="updateArticleFn">修改文章</el-button>
      <el-button>重置</el-button>
    </div>

  </el-form-item>
</el-form>
    </el-card>
  </div>
</template>

<script>
// 3.导入获取文章详情的接口函数
import { punlishArticleApi, getArticleDetailAPI, updatedArticleAPI } from '@/api/Publish'
import { getAllChannelListAPI } from '@/api/Article'
import { ARTICLE_COVER_LIST } from '@/constant'
import { VUE_APP_UPLOAD_URL } from '@/app.config' // 1.导入图篇url地址
export default {
  name: 'Publish',
  data () {
    return {
      // 1.发布文章的表单对象校验规则
      //   参考文档Form表单->表单验证
      rules: {
        // 3.标题规则
        title: [{
          required: true,
          message: '请输入标题',
          trigger: ['blur', 'change']
        },
        {
          min: 1,
          max: 10,
          message: '标题长度在1-10个字符',
          trigger: ['blur', 'change']
        }],
        // 4.内容规则
        content: [{
          required: true,
          message: '请输入内容',
          trigger: ['blur', 'change']
        },
        {
          min: 10,
          max: 1000,
          message: '内容长度在10-1000个字符',
          trigger: ['blur', 'change']
        }],
        // 5.选择频道规则
        channel_id: [
          {
            required: true,
            message: '请选择频道',
            trigger: ['blur', 'change']
          }],
        // 6.封面规则(由于cover.type不是一个变量名,所以要加'')
        //   这里用到文档->Form表单->自定义校验规则
        //   validator:函数 传入三个参数rule, value, callback
        //   如果校验出错, callback(new Error(错误原理))
        //   如果校验成功, callback()
        'cover.type': [
          {
            validator: (rule, value, callback) => {
              // console.log(rule)
              // console.log(value)
              // console.log(callback)
              // 如果选择的封面type与上传的图片数量不一致
              if (value >= 1 && value !== this.publishForm.cover.images.length) {
                // 就利用callback回调函数生成一个错误对象new Error
                callback(new Error('请选择封面'))
                // 当图片上传成功之后需要清除校验,这个写在图片上传成功的函数里
              } else {
                callback()
              }
            },
            trigger: 'change'
          }]
      },

      VUE_APP_UPLOAD_URL,
      allChannelList: [],
      publishForm: {
        title: '',
        content: '',
        cover: {
          type: 1,
          images: []
        },
        channel_id: 0
      },
      coverList: ARTICLE_COVER_LIST

    }
  },
  methods: {
    // 3.修改文章
    updateArticleFn () {
      this.$refs.publishFormRef.validate(async valid => {
        if (!valid) return
        // 调用修改文章接口
        await updatedArticleAPI({
          artId: this.$route.query.targetId,
          ...this.publishForm
        })
      })
      // 跳转到内容管理页
      this.$router.push('/layout/article')
    },
    async publishArticleFn (draft) {
      await punlishArticleApi({ draft, ...this.publishForm })
      this.$message({
        type: 'success',
        message: '发布成功'
      })
      this.$router.push('/layout/article')
    },

    // 2.封面上传前的钩子,返回false则停止上传,返回true继续
    onBeforeUploadFn (file) {
      // console.log(file)
      // 3.获取有用的信息:name,size
      const { name, size } = file
      // 判断类型
      if (!/\.(png|jpe?g)$/i.test(name)) {
        this.$message({
          type: 'warning',
          message: '仅支持png,jpg,jpep图片格式'
        })
        return false
      }
      // 判断大小
      // 1KB=1024B
      // 1M=1024KE
      // 1G=1024M
      // 1T=1024G
      if (size / 1024 / 1024 > 1) {
        this.$message({
          type: 'warning',
          message: '图片不能超过1M'
        })
        return false
      }
    },
    // 封面类型切换事件
    onCoverTypeChangeFn () {
      if (this.publishForm.cover.images.length) {
        this.publishForm.cover.images = [this.publishForm.cover.images[0]]
        // 6.当三图切换单图时,也要关闭校验
        if (this.publishForm.cover.type === this.publishForm.cover.images.length) {
          this.$refs.publishFormRef.clearValidate('cover.type')
        }
      }
    },

    // 超过限制时的提示信息
    onUploadExceedFn () {
      this.$message({
        type: 'warning',
        message: `当前最多只能上传${this.publishForm.cover.type}张`
      })
    },
    // 封面上传成功的回调函数
    onUploadSuccessFn (resp) {
      // console.log(resp)
      this.publishForm.cover.images.push(resp.data.url)
      // 6.清除校验 文档Form表单->Form Methods->clearValidate
      //   图片上传成功,选择封面type与上传的图数量一致,就清除校验
      if (this.publishForm.cover.type === this.publishForm.cover.images.length) {
        this.$refs.publishFormRef.clearValidate('cover.type')
      }
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 4.富文本编辑器内容校验
    onEditorChangeFn ({ text }) {
      this.publishForm.content = text.replaceAll('\n', '')
      // console.log(this.publishForm.content)

      // 4.新增校验
      this.$refs.publishFormRef.validateField('content')
    },
    // 删除封面的函数
    onUploadRemoveFn (file) {
      // console.log(file)
      // filter 或indexOf + splice
      this.publishForm.cover.images = this.publishForm.cover.images.filter(url => url !== file.url)
      // 6.当删除封面时也需要判断一下是否要清除校验
      if (this.publishForm.cover.type === this.publishForm.cover.images.length) {
        // 关闭校验
        this.$refs.publishFormRef.clearValidate('cover.type')
      } else {
        // 开启校验
        this.$refs.publishFormRef.validateField('cover.type')
      }
    }
  },
  // 3.调用接口函数拿到数据赋值给数组
  async created () {
    const resp = await getAllChannelListAPI()
    this.allChannelList = resp.data.data.channels

    // 获取文章详情
    // 2.判断targetId有值,说明是从编辑页过来的,再去获取文章详情
    const { targetId } = this.$route.query
    if (!targetId) return
    const resp2 = await getArticleDetailAPI({
      artId: targetId
    })
    // console.log(resp2)
    // 5.把获取到的数据显示到页面中
    this.publishForm = { ...this.publishFormRef, ...resp2.data.data }
  },
  computed: {
    // 1.计算得到的文件展示列表
    showFileList () {
      // 2.通过map方法把images数组中的url转换成{name,url}形式的对象,再赋值给标签的file-list属性
      return this.publishForm.cover.images.map((url, index) => {
        return {
          name: `item${index + 1}.jpg`,
          url
        }
      })
    }
  }
}
</script>

<style>
/* 2.改一下富文本编辑器的高度 */
.ql-container{
  height: 12.5rem;
}
</style>
